package org.bovver.service;

import org.bovver.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by Paul on 2014/11/25.
 */
@Service
public class UserService {
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<User> getUsers() {
        List<User> users = jdbcTemplate.query("SELECT * FROM USER", new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.setPassword(resultSet.getString("password"));
                user.setUsername(resultSet.getString("username"));
                return user;
            }
        });

        return users;
    }

    public List<User> getMoreUsers(int last, int size) {
        List<User> users = jdbcTemplate.query(
                "select * from (SELECT * FROM shopxx.xx_product order by id desc) p where p.id < ? limit ?",
                new Object[]{last, size},
                new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.setPassword(resultSet.getString("full_name"));
                user.setUsername(resultSet.getString("name"));
                user.setId(resultSet.getInt("id"));
                return user;
            }
        });

        return users;
    }
}
